package com.kuzan.autocloud.client.sys.helper;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Description: </p>
 *
 * @author kuzank
 */
@Service
@Transactional
public class AcSqlHelper<T> {

    @Autowired
    private EntityManager entityManager;


    public Integer excute(String sql) {
        return excute(sql, new HashMap<>());
    }

    public Integer excute(String sql, Map<String, Object> params) {
        Query query = entityManager.createNativeQuery(sql);
        params.forEach((key, val) ->
                query.setParameter(key, val)
        );
        return query.executeUpdate();
    }

    public List<T> query(String sql) {
        return query(sql, new HashMap<>());
    }

    public List<T> query(String sql, Map<String, Object> params) {
        Query query = entityManager.createNativeQuery(sql);
        params.forEach((key, val) ->
                query.setParameter(key, val)
        );
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<T> rows = query.getResultList();
        return rows;
    }

    public T queryOne(String sql) {
        return queryOne(sql, new HashMap<>());
    }

    public T queryOne(String sql, Map<String, Object> params) {
        Query query = entityManager.createNativeQuery(sql);
        params.forEach((key, val) ->
                query.setParameter(key, val)
        );
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<T> rows = query.getResultList();
        if (null != rows && rows.size() > 0) {
            return rows.get(0);
        }
        return null;
    }
}
